#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/10/27 13:55
# @Author : 闫峰
# @File    : commonUtils.py
from common.baserequest import Base_request, json_regular
from utils.mysqlUtils.db_pool import Database
import os
from common.setting import ensure_path_sep
from utils.mysqlUtils.es_utils import Es_utils
from utils.mysqlUtils.mongodb_utils import MongoDBLink

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


# info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
# error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
# warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
# remove_file(info_path)
# remove_file(error_path)
# remove_file(warning_path)
# INFO = LogHandler(info_path, level='info')
# ERROR = LogHandler(error_path, level='error')
# WARNING = LogHandler(warning_path, level='warning')

platform_mapping = {
    67: "allegro",
    57: "aliexpress",
    58: "lazada",
    70: "mercadolibre",
    97: "shopeev2",
    45: "walmart",
}


class Common_utils:
    br = Base_request()
    es = Es_utils(username="elastic", password="CoMHLgfpD7dxcA5dYFPK", ip="10.158.158.165", port="9201")
    modb = MongoDBLink(uri='mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin',
                       dbname='zhcxkj_riskworker', coll_name='Kogan_Listing_Sensitive')
    znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")

    # def listing_filter_insert_mongodb(self, es_check_listing, platformId):
    #
    #     for i in es_check_listing:
    #
    #         esid = i['Id']
    #         check_data = i['Title'] + " " + i['Description']
    #         sku = i['Sku']
    #         categoryPathId = self.get_categoryPathId(sku,platformId)
    #         res = self.hebingjiekou(check_data, categoryPathId, platformId)
    #         if res['status'] == 'success':
    #             data = res['data'][0]
    #             if len(data['SensitiveWords']) != 0:
    #                 for a in data['SensitiveWords']:
    #                     SensitiveId = str(a['SensitiveId'])
    #                     self.check_SensitiveWords(esid, SensitiveId)
    #
    #             if len(data['BrandWords']) != 0:
    #                 for b in data['BrandWords']:
    #                     SensitiveId = b["BrandEsId"]
    #                     self.check_BrandWords(esid, SensitiveId)
    #
    #         else:
    #             ERROR.logger.error(f"合并接口报错check_data={check_data}")
    #
    # def check_SensitiveWords(self, esid, SensitiveId):
    #     filter_sen = {"SensitiveType": 2, "EsId": esid, "SensitiveId": SensitiveId}
    #     mongodb_res = self.modb.select(filter_sen)
    #     if len(mongodb_res) != 0:
    #         pass
    #     else:
    #         ERROR.logger.error(f"{filter_sen}验证失败")
    #
    # def check_BrandWords(self, esid, SensitiveId):
    #     filter_brand = {"SensitiveType": 1, "EsId": esid, "SensitiveId": SensitiveId}
    #     mongodb_res = self.modb.select(filter_brand)
    #     if len(mongodb_res) != 0:
    #         pass
    #     else:
    #         ERROR.logger.error(f"{filter_brand}验证失败")
    #
    # def hebingjiekou(self, text, categoryPathId, platformId):
    #     data = {
    #         "input": {
    #             "platformId": platformId,
    #             "siteCode": "",
    #             "categoryPathId": categoryPathId,
    #             "keyWords": [text],
    #             "isFilterd": 1,
    #         }
    #     }
    #
    #     res = self.br.post_auth(url='http://riskapi.zhcxkj.com/Product/GetSensitive', data=data, user='apiuser',
    #                             pwd='z8_h92c-o0Oxik1j')
    #     return res
    #
    # def get_categoryPathId(self, sku,platformId):
    #     platform_name = platform_mapping.get(platformId)
    #     get_OtherNodeId = f"""
    #     SELECT OtherNodeId FROM m_{platform_name}_sku_marketcategory WHERE Sku=%s AND IsDelete=0
    #     """
    #     OtherNodeId = self.znkd_db.fetch_all(get_OtherNodeId, (sku,))
    #     if len(OtherNodeId):
    #         OtherNodeId = OtherNodeId[0].get('OtherNodeId')
    #     else:
    #         ERROR.logger.error(f"sku={sku}没有查询到OtherNodeId")
    #     return OtherNodeId


    def get_different_keys(self,expect_dict,actual_dict,ERROR):
        different_keys = []
        try:
            different_keys = [key for key in expect_dict if expect_dict[key] != actual_dict[key]]
        except Exception as e:
            ERROR.logger.error(f"异常，数据如下")
            print("expect_dict",expect_dict)
            print("actual_dict",actual_dict)
            return
        ERROR.logger.error(f"Id={expect_dict['Id']}同步失败,比对不一致的key{different_keys}")
        for key in different_keys:
            ERROR.logger.error(f"expect_dict[{key}]={expect_dict[key]}")
            ERROR.logger.error(f"actual_dict=[{key}]={actual_dict[key]}")
        # print(different_keys)


if __name__ == '__main__':
    dict1 = {"a": 11, "b": 2, "c": 3}
    dict2 = {"a": 1, "b": 4, "c": 3}
    # Common_utils().get_categoryPathId("16840226",45)
    Common_utils().get_different_keys(dict1,dict2)